<template>
  <el-dialog
      v-model="visible"
      :title="type === 'create' ? '新增用户' : '编辑用户'"
      width="600px"
      destroy-on-close
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            type="email"
        />
      </el-form-item>

      <el-form-item label="角色" prop="role">
        <el-select
            v-model="formData.role"
            placeholder="请选择角色"
            style="width: 100%"
        >
          <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="type === 'create'" label="密码" prop="password">
        <el-input
            v-model="formData.password"
            placeholder="请输入密码"
            type="password"
            show-password
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const props = defineProps({
  modelValue: Boolean,
  type: {
    type: String,
    default: 'create'
  },
  currentData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()
const formRef = ref()
const visible = ref(false)

// 表单数据
const defaultFormData = {
  username: '',
  email: '',
  role: 'user',
  password: '',
  status: 1
}

const formData = reactive({ ...defaultFormData })

// 表单规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '长度3-16个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度6-20个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
})

// 角色选项
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'user', label: '普通用户' }
]

// 监听显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) initFormData()
})

// 初始化表单数据
const initFormData = () => {
  Object.assign(formData, defaultFormData)
  if (props.type === 'edit' && props.currentData) {
    Object.keys(defaultFormData).forEach(key => {
      if (props.currentData[key] !== undefined) {
        formData[key] = props.currentData[key]
      }
    })
    // 编辑时不需要密码字段
    delete formData.password
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const params = { ...formData }
    if (props.type === 'create') {
      await userStore.createUser(params)
      ElMessage.success('创建成功')
    } else {
      await userStore.updateUser(props.currentData.id, params)
      ElMessage.success('更新成功')
    }

    emit('success')
    visible.value = false
  } catch (error) {
    console.error('表单提交失败:', error)
  }
}

// 双向绑定处理
watch(visible, (val) => {
  emit('update:modelValue', val)
})
</script>